package org.ljy.forum6.interceptor;

import org.ljy.forum6.common.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *  需要拦截的情况（未找到session）规则
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //设置跳转路径
    @Value("${bit-forum.login.url}")
    private String defaultURL;

    /**
     *
     * @return true--允许访问  false--禁止访问
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session
        HttpSession session = request.getSession(false);
        //2.不为空,允许访问
        if (session != null &&  session.getAttribute(AppConfig.USER_SESSION) != null) {
            return true;
        }
        //3.验证不通过，跳转登录界面
        if (!defaultURL.startsWith("/")) {
            defaultURL = "/" + defaultURL;
        }
        response.sendRedirect(defaultURL);
        return false;
    }
}
